package com.k1998.mybatis.controller;

import com.alibaba.fastjson.JSON;
import com.k1998.mybatis.bean.Img;
import com.k1998.mybatis.utils.QueryInfo;
import com.k1998.mybatis.dao.IUploadFileDao;
import com.k1998.mybatis.service.QiniuService;
import com.qiniu.http.Response;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/upload")
@Api(tags = {"七牛云上传Api文档"})
public class UploadFileController {
    @Autowired
    private QiniuService qiniuService;
    @Autowired
    private IUploadFileDao iUploadFileDao;

    @PostMapping("/img")
    public String register(@RequestParam(value = "file") MultipartFile  multipartFile ) throws Exception {
        String url = qiniuService.uploadFile(multipartFile.getInputStream());
        String surl = "http://" + url;
        int i = iUploadFileDao.insertImg(surl);
        String str = i >0?"success":"error";
        HashMap<String, Object> res = new HashMap<>();
        res.put("data",surl);
        res.put("code",str);
        String users_json = JSON.toJSONString(res);
        return users_json;
    }

    @PostMapping("/findAllImg")
    public String findAllImg(@RequestBody QueryInfo queryInfo ) throws Exception {
        // 查询到的结果数量
        int numbers = iUploadFileDao.getCounts("%"+queryInfo.getQuery()+"%");
        // 第几条数据开始
        int pageStart = (queryInfo.getPageNum()-1)*queryInfo.getPageSize();
        List<Img> imgs = iUploadFileDao.findAllImg("%"+queryInfo.getQuery()+"%",pageStart,queryInfo.getPageSize());
        HashMap<String, Object> res = new HashMap<>();
        res.put("numbers",numbers);
        res.put("data",imgs);
        res.put("code","success");
        String users_json = JSON.toJSONString(res);
        return users_json;

    }


    @GetMapping("delete/{key}")
    public Response deleteFile(@PathVariable String key) throws IOException {
        return qiniuService.delete(key);
    }

}
